﻿using Blm.PgsqlDriver.Helpers;
using Blm.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Domain.DtoModel.MiniApp;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Domain.UnitOfWork;

namespace VisionCloud.Domain.Repository.Implement.Ms
{
    public class MsTaskDotCloudBatchRepository : BaseRepository<MsTaskDotCloudBatch>, IMsTaskDotCloudBatchRepository
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public async ValueTask<bool> AddDotCloudBatchAsync(DotCloudUploadBatchDto dto)
        {
            var model = await this.FirstOrDefaultAsync(p => p.BatchId == dto.BatchId);
            if (model != null)
                return false;

            model = new MsTaskDotCloudBatch
            {
                BatchId = dto.BatchId,
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                Status = 2,
                TaskId = dto.TaskId,
                PointIndexs = dto.PointIndexs.OrderBy(p => p).ToArray(),
                CurrTimes = 0,
                MaxTimes = 1,
                IsDeleted = false
            };

            this.Add(model, false);
            var count = await UnitOfWork.SaveChangesAsync();
            return count > 0;
        }

        public async ValueTask<bool> AddDotCloudBatchAsync(TaskDotCloudBatchRequestDto dto)
        {
            List<MsTaskDotCloudBatch> list = new List<MsTaskDotCloudBatch>();
            foreach (var item in dto.TaskBatchList)
            {
                list.Add(new MsTaskDotCloudBatch
                {
                    BatchId = Guid.NewGuid(),
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    CurrTimes = 0,
                    IsDeleted = false,
                    MaxTimes = 1,
                    Status = 2,
                    TaskId = item.TaskId,
                    PointIndexs = item.IndexArr.OrderBy(p => p).Select(p => p.ToString("D3")).ToArray()
                });
            }

            this.AddRange(list, false);
            var count = await UnitOfWork.SaveChangesAsync();
            return count > 0;
        }

        public async ValueTask<bool> UpdateCurrTimes(Guid batchId)
        {
            var sql = $@"UPDATE ""MsTaskDotCloudBatch"" set ""CurrTimes"" = ""CurrTimes"" + 1, ""UpdateDate"" = '{DateTime.Now.ToDateTimeStandardString()}' where ""BatchId"" = '{batchId}'";
            var total = await PgSqlHelper.ExecuteNonQueryAsync(CommandType.Text, sql);
            return total > 0;
        }
    }
}
